package org.streets.database.internal;

import java.lang.reflect.Method;

import org.apache.tapestry5.ioc.Invocation;
import org.apache.tapestry5.ioc.MethodAdvice;
import org.apache.tapestry5.ioc.MethodAdviceReceiver;
import org.streets.database.SQLConnectionManager;
import org.streets.database.SQLTransactionAdvisor;
import org.streets.database.annotations.CommitAfterInvoke;
/**
 * 可以在一个事务中提交一部分事务然后继续启动下面的事务
 * @author dzb
 */
public class SQLTransactionAdvisorImpl implements SQLTransactionAdvisor {

	private final SQLConnectionManager manager;
	
	public SQLTransactionAdvisorImpl(SQLConnectionManager manager) {
		this.manager = manager;
	}
	
	public void addCommitTransactionAdvice(MethodAdviceReceiver receiver) {
		for (Method m : receiver.getInterface().getMethods())
        {
            if (m.getAnnotation(CommitAfterInvoke.class) != null)
            {
                receiver.adviseMethod(m, advice);
            }
        }		
	}

    /**
     * The rules for advice are the same for any method: commit on success or checked exception, abort on thrown
     * exception ... so we can use a single shared advice object.
     */
    private final MethodAdvice advice = new MethodAdvice()
    {
        public void advise(Invocation invocation)
        {
            try
            {
                invocation.proceed();
            }
            catch (RuntimeException ex)
            {
                manager.abort();
                throw ex;
            }
            // For success or checked exception, commit the transaction.
            manager.commit();
            // begin a new transaction 
            manager.begin();
        }
    };
}
